package com.boomsecret.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author wangjinliang on 2019/1/16.
 */
public class BIOClientDemo {

    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            socket = new Socket("127.0.0.1", 8080);
            // request
            outputStream = socket.getOutputStream();
            outputStream.write("request content.".getBytes("utf-8"));
            outputStream.flush();
            socket.shutdownOutput();

            // response
            inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            StringBuilder response = new StringBuilder();
            int length;
            if ((length = inputStream.read(bytes)) != -1) {
                response.append(new String(bytes, 0, length));
            }
            System.out.println("response:" + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
